<template>
  <el-dialog
    v-model="visible"
    title="入住客户信息登记"
    width="900px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    draggable
    class="add-checkin-dialog"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="110px"
      class="main-form"
    >
      <!-- 第一行 -->
      <el-row :gutter="18">
        <el-col :span="8">
          <el-form-item label="客户姓名" prop="name">
            <el-input v-model="form.name" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" readonly placeholder="自动计算" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row :gutter="18">
        <el-col :span="8">
          <el-form-item label="出生日期" prop="birthdate">
            <el-date-picker v-model="form.birthdate" value-format="YYYY-MM-DD" placeholder="选择出生日期" style="width: 100%"
              @change="onBirthdateChange" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="form.idNumber" maxlength="18" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="老人电话" prop="phone">
            <el-input v-model="form.phone" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="18">
        <el-col :span="8">
          <el-form-item label="家庭联系人" prop="familyContactName">
            <el-input v-model="form.familyContactName" placeholder="联系人姓名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="家庭电话" prop="familyContactPhone">
            <el-input v-model="form.familyContactPhone" placeholder="联系人电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="血型" prop="bloodType">
            <el-select v-model="form.bloodType" placeholder="请选择" style="width:100%">
              <el-option label="A" value="A" />
              <el-option label="B" value="B" />
              <el-option label="AB" value="AB" />
              <el-option label="O" value="O" />
              <el-option label="暂时未知" value="unknown" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
      <el-row :gutter="18">
        <el-col :span="8">
          <el-form-item label="入住日期" prop="checkinDate">
            <el-date-picker v-model="form.checkinDate" value-format="YYYY-MM-DD" placeholder="选择入住日期" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束日期" prop="contractEndDate">
            <el-date-picker v-model="form.contractEndDate" value-format="YYYY-MM-DD" placeholder="选择合同结束日期" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="办理人" prop="userId">
            <el-input :value="username" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行（床位选择） -->
      <el-row :gutter="18">
        <el-col :span="12">
          <el-form-item label="房间选择" prop="bedId">
            <el-cascader v-model="roomCascader" :options="roomCascaderOptions" :props="roomCascaderProps"
              placeholder="选择房间" filterable clearable @change="onRoomCascaderChange" style="width: 49%; margin-right:2%;" />
            <el-select v-model="form.bedId" :disabled="!bedOptions.length" filterable clearable placeholder="选择床位号"
              style="width: 49%;">
              <el-option v-for="bed in bedOptions" :key="bed.bedId" :label="`${bed.bedNumber}号`" :value="bed.bedId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="notes">
            <el-input v-model="form.notes" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 饮食配置区 -->
    <el-divider style="margin: 30px 0 18px 0; color: #aaa;">饮食配置选项</el-divider>
    <el-form ref="mealFormRef" :model="mealConfig" label-width="110px" class="meal-form">
      <el-row :gutter="18">
        <el-col :span="6">
          <el-form-item label="盐分选择" prop="saltId">
            <el-radio-group v-model="mealConfig.saltId">
              <el-radio label="低盐">低盐</el-radio>
              <el-radio label="中盐">中盐</el-radio>
              <el-radio label="高盐">高盐</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="油脂选择" prop="oil">
            <el-radio-group v-model="mealConfig.oil">
              <el-radio label="低油">低油</el-radio>
              <el-radio label="中油">中油</el-radio>
              <el-radio label="高油">高油</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="糖分选择" prop="sugar">
            <el-radio-group v-model="mealConfig.sugar">
              <el-radio label="无糖">无糖</el-radio>
              <el-radio label="代糖">代糖</el-radio>
              <el-radio label="低糖">低糖</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="饮食类型" prop="diettype">
            <el-radio-group v-model="mealConfig.diettype">
              <el-radio label="普食">普食</el-radio>
              <el-radio label="软食">软食</el-radio>
              <el-radio label="流质">流质</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="18">
        <el-col :span="24">
          <el-form-item label="饮食备注" prop="description">
            <el-input v-model="mealConfig.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入饮食相关备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button type="info" @click="handleReset">重置</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose, inject, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'


console.log(11, localStorage.getItem('username'))
console.log(12, localStorage.getItem('userId'))

// 基础数据
const axios = inject('axios')
const visible = ref(false)
const loading = ref(false)
const username = localStorage.getItem('username')

// 多级床位选择
const allFreeBeds = ref([])
const roomCascaderOptions = ref([])
const roomCascader = ref([])
const bedOptions = ref([])
const roomCascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: false,
  emitPath: true
}

// 表单模型
const form = reactive({
  name: '',
  gender: '男',
  age: 0,
  birthdate: '',
  idNumber: '',
  familyContactName: '',
  familyContactPhone: '',
  bloodType: '',
  phone: '',
  checkinDate: '',
  contractEndDate: '',
  bedId: null,
  nursingLevel: 0,
  healthButler: null,
  notes: '',
  userId: '', // 提交时设置
})

// 饮食配置表单
const mealConfig = reactive({
  saltId: '',
  oil: '',
  sugar: '',
  diettype: '',
  description: ''
})

// 校验规则
const rules = {
  name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  birthdate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  idNumber: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  checkinDate: [{ required: true, message: '请选择入住日期', trigger: 'change' }],
  contractEndDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value || !form.checkinDate) return callback()
        if (new Date(value) < new Date(form.checkinDate)) {
          return callback(new Error('合同到期时间不能小于入住日期'))
        }
        callback()
      },
      trigger: 'change'
    }
  ],
  bedId: [{ required: true, message: '请选择床位', trigger: 'change' }]
}

const formRef = ref()
const mealFormRef = ref()

// 年龄自动计算
function onBirthdateChange(val) {
  form.age = calcAge(val)
}
function calcAge(birthdate) {
  if (!birthdate) return ''
  const birth = new Date(birthdate)
  const today = new Date()
  let age = today.getFullYear() - birth.getFullYear()
  const m = today.getMonth() - birth.getMonth()
  if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--
  return age > 0 ? age : 0
}

// 打开弹窗
const open = async () => {
  visible.value = true
  Object.assign(form, {
    name: '', gender: '男', age: '', birthdate: '', idNumber: '',
    familyContactName: '', familyContactPhone: '', bloodType: '', phone: '',
    checkinDate: '', contractEndDate: '', bedId: null,
    nursingLevel: 0, healthButler: null, notes: '', userId: ''
  })
  Object.assign(mealConfig, { saltId: '', oil: '', sugar: '', diettype: '', description: '' })
  roomCascader.value = []
  bedOptions.value = []
  try {
    const { data } = await axios.get('http://localhost:9000/bed/getFreeNum')
    allFreeBeds.value = Array.isArray(data.data) ? data.data : Object.values(data.data).flat()
    roomCascaderOptions.value = buildRoomCascader(allFreeBeds.value)
  } catch {
    allFreeBeds.value = []
    roomCascaderOptions.value = []
    ElMessage.error('空闲床位加载失败')
  }
}

// 构建楼栋-楼层-房间号多级选项
function buildRoomCascader(beds) {
  const res = []
  beds.forEach(item => {
    let buildingNode = res.find(x => x.value === item.building)
    if (!buildingNode) {
      buildingNode = { value: item.building, label: `${item.building}栋`, children: [] }
      res.push(buildingNode)
    }
    let floorNode = buildingNode.children.find(x => x.value === item.floorNumber)
    if (!floorNode) {
      floorNode = { value: item.floorNumber, label: `${item.floorNumber}层`, children: [] }
      buildingNode.children.push(floorNode)
    }
    let roomNode = floorNode.children.find(x => x.value === item.roomNumber)
    if (!roomNode) {
      roomNode = { value: item.roomNumber, label: `${item.roomNumber}房` }
      floorNode.children.push(roomNode)
    }
  })
  return res
}

// 选房间时动态刷新床位号
function onRoomCascaderChange(val) {
  if (!val || val.length < 3) {
    bedOptions.value = []
    form.bedId = ''
    return
  }
  const [building, floorNumber, roomNumber] = val
  bedOptions.value = allFreeBeds.value.filter(
    b => b.building === building && b.floorNumber === floorNumber && b.roomNumber === roomNumber
  )
  form.bedId = ''
}

// 拼接家庭联系人
function getFullFamilyContact() {
  if (!form.familyContactName && !form.familyContactPhone) return ''
  if (form.familyContactName && form.familyContactPhone) {
    return `${form.familyContactName}（${form.familyContactPhone}）`
  }
  return form.familyContactName || form.familyContactPhone
}

// 重置
const handleReset = () => {
  formRef.value.resetFields()
  mealFormRef.value.resetFields()
  roomCascader.value = []
  bedOptions.value = []
}

// 提交
const emit = defineEmits(['success', 'cancel'])
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      let userId = localStorage.getItem('userId') // 你可改为 session 存储 userId
      form.userId = userId

      const payload = {
        client: {
          ...form,
          familyContact: getFullFamilyContact(),
          nursingLevel: 0,
          healthButler: null
        },
        mealConfig: { ...mealConfig }
      }
      // 不提交冗余前端表单字段
      delete payload.client.familyContactName
      delete payload.client.familyContactPhone
      console.log(666, userId)

      const { data } = await axios.post('http://localhost:9000/client/checkin', payload)
      if (data.status === 200) {
        ElMessage.success('添加成功')
        visible.value = false
        emit('success')
      } else {
        ElMessage.warning(data.msg || '提交失败')
      }
    } catch {
      ElMessage.error('提交失败')
    } finally {
      loading.value = false
    }
  })
}

defineExpose({ open })
</script>  

<style scoped>
.add-checkin-dialog .el-dialog__body {
  padding: 24px 30px 12px 30px;
  background: #f9fafc;
}
.main-form, .meal-form {
  background: #fff;
  border-radius: 10px;
  padding: 18px 14px 4px 14px;
  box-shadow: 0 1px 4px 0 rgba(0,0,0,0.04);
  margin-bottom: 6px;
}
.el-form-item {
  margin-bottom: 16px;
}
.el-row {
  margin-bottom: 2px;
}
.el-divider {
  font-size: 16px;
  font-weight: 500;
  color: #666;
}
</style>

  